const util = require('./util')
const api = require('./api')
const mongo = require('./db_helper')
const timer = require('./timer')

const logger = util.getLogger('service')

let services = []     //格式：{name, status, lastTime, error}

const RUN_CYCLE = 300000

const checkTimer = () => {
  let now = new Date().getTime()
  let service = {
    name: '定时器',
    status: '正常',
    lastTime: new Date().format('yyyy-MM-dd HH:mm:ss')
  }
  for (v of services) {
    let lastRun = new Date(v.lastTime).getTime()
    if (now - lastRun > RUN_CYCLE) {
      service.status = '异常'
      return service
    }
  }
  return service
}

const checkMongo = async () => {
  let service = {
    name: 'mongoDB',
    status: '正常',
    lastTime: new Date().format('yyyy-MM-dd HH:mm:ss')
  }
  try{
    let count = await mongo.jobs.count()
  } catch(e) {
    service.status = '异常'
    service.error = e.message
  }
  return service
}

const checkLivy = async () => {
  let service = {
    name: 'Livy',
    status: '正常',
    lastTime: new Date().format('yyyy-MM-dd HH:mm:ss')
  }
  try{
    let res = await util.callLivy(api.getBatches)
  } catch(e) {
    service.status = '异常'
    service.error = e.message
  }
  return service
}

//检测磁盘空间
const checkDisk = async () => {
  let service = {
    name: '磁盘空间',
    status: '正常',
    lastTime: new Date().format('yyyy-MM-dd HH:mm:ss')
  }
  try{
    let out = await util.runExec('df -h')
    service.error = out.stdout
  } catch(e) {
    service.status = '异常'
    service.error = e.message
  }
  return service
}

timer.addTask({
  name: 'check-services',
  cycle: RUN_CYCLE,
  async fun () {
    try {
      services = []
      let result = checkTimer()
      services.push(result)
      result = await checkMongo()
      services.push(result)
      result = await checkLivy()
      services.push(result)
      result = await checkDisk()
      services.push(result)
    } catch (e) {
      logger.debug('监控任务运行异常：', e)
      services = [{
        name: '监控任务',
        status: '异常',
        lastTime: new Date('yyyy-MM-dd HH:mm:ss'),
        error: e.message
      }]
    }
  }
})

module.exports = {
  getStatus () {
    return services
  }
}